package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.constant.ChatType;
import com.domain.entity.ChatMessage;
import com.domain.entity.User;
import com.domain.entity.UserSession;
import com.mapper.ChatMessageMapper;
import com.service.ChatMessageService;
import com.service.UserFriendService;
import com.service.UserSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Administrator
 * @description 针对表【chat_message】的数据库操作Service实现
 * @createDate 2024-05-21 20:28:29
 */
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage>
        implements ChatMessageService {
    private static final Integer DATA_NUM = 50;
    @Autowired
    UserFriendService userFriendService;
    @Autowired
    private UserSessionService userSessionService;


    /**
     * 根据时间段获取聊天记录
     *
     * @param minTime
     * @param maxTime
     * @param receiveId
     * @param type
     * @param loginUser
     * @return
     */
    public List<ChatMessage> getChatMessages(long minTime, long maxTime, long receiveId, Integer type, User loginUser,long currentTime) {
        //只能查询到现在
        maxTime = Math.min(maxTime, System.currentTimeMillis());
        //从数据库中搜索消息
        QueryWrapper<ChatMessage> chatMessageQueryWrapper = new QueryWrapper<>();
        if (type.equals(ChatType.PRIVATE)) {
            chatMessageQueryWrapper.and(wrapper -> wrapper
                    .eq("receive_id", receiveId)
                    .eq("sender_id", loginUser.getId())
                    .or(wrapperOr -> wrapperOr
                            .eq("receive_id", loginUser.getId())
                            .eq("sender_id", receiveId)));
        } else {
            chatMessageQueryWrapper
                    .eq("receive_id", receiveId)
                    .eq("sender_id", loginUser.getId());
        }
        chatMessageQueryWrapper.gt("send_time", minTime)
                .lt("send_time", maxTime)
                .eq("type", type)
                .last("limit " + DATA_NUM)
                .orderByAsc("send_time");

        //更新最后一次查看历史记录的时间
        UpdateWrapper<UserSession> wrapper = new UpdateWrapper<>();
        wrapper.set("last_select_time",currentTime).eq("user_id", loginUser.getId()).eq("session_id", receiveId);
        userSessionService.update(wrapper);
        return list(chatMessageQueryWrapper);
    }
}




